!> author: 左志华
!> date: 2022-07-20
!>
!> lua API <br>
!> Lua 接口
module sph_load_lua

    use, intrinsic :: iso_c_binding, only: c_ptr
    use lua
    use seakeeping_logger, only: stdlog => global_logger
    use easy_lua_m, only: get_value
    use seakeeping_kinds, only: rk
    use seakeeping_string, only: to_string
    use seakeeping_filesystem, only: is_exist
    use seakeeping_error_handling, only: file_not_found_error, file_parse_error
    use sph_region_type, only: region_t
    use sph_terminal, only: error
    implicit none

    public :: load_lua_script

contains

    !> Load Lua script <br>
    !> 读取 lua 脚本
    impure subroutine load_lua_script(lua_script, region)
        character(*), intent(in) :: lua_script  !! Lua script <br>
                                                !! lua 脚本
        type(region_t), intent(out) :: region   !! region <br>
                                                !! 粒子域
        type(c_ptr) :: lua_state

        integer :: status

        if (.not. is_exist(lua_script)) call file_not_found_error(lua_script)

        lua_state = lual_newstate()
        call lual_openlibs(lua_state)
        status = lual_loadfile(lua_state, lua_script)
        if (status /= 0) call file_parse_error(lua_script, '无法加载脚本文件')

        status = lua_pcall(lua_state, 0, 0, 0)
        if (status /= 0) call file_parse_error(lua_script, '脚本运行错误')

        status = lua_getglobal(lua_state, 'region')
        ! if (status /= 0) then
        !     call error_stop('Error getting region from script: '//lua_script, &
        !                     'sph_load_lua%load_lua_script')
        ! end if

        status = lua_pcall(lua_state, 0, 10, 0)
        if (status /= 0) call file_parse_error(lua_script, '脚本函数 region 运行错误')

        call get_value(lua_state, region%loc, index=-10)
        call get_value(lua_state, region%vel, index=-9)
        call get_value(lua_state, region%mass, index=-8)
        call get_value(lua_state, region%rho, index=-7)
        call get_value(lua_state, region%p, index=-6)
        call get_value(lua_state, region%u, index=-5)
        call get_value(lua_state, region%itype, index=-4)
        call get_value(lua_state, region%hsml, index=-3)
        call get_value(lua_state, region%nreal, index=-2)
        call get_value(lua_state, region%nvirt, index=-1)
        call lua_close(lua_state)

        region%dim = size(region%loc, 1)
        region%ntotal = region%nreal + region%nvirt

        call stdlog%log_information('Loaded region from script: '//lua_script)
        call stdlog%log_information('Region:')
        call stdlog%log_information('nreal = '//to_string(region%nreal))
        call stdlog%log_information('nvirt = '//to_string(region%nvirt))
        call stdlog%log_information('dim = '//to_string(region%dim))
        call stdlog%log_information('hsml = '//to_string(region%hsml))

    end subroutine load_lua_script

end module sph_load_lua
